package edu.ubb.scp.logic;

import java.util.ArrayList;

import edu.ubb.scp.dao.BaseDAO;
import edu.ubb.scp.dao.DAOFactory;
import edu.ubb.scp.model.Customer;
import edu.ubb.scp.model.Model;
import edu.ubb.scp.model.Order;
import edu.ubb.scp.model.Product;

public class Bill {
	private ArrayList<Model> orders;
	
	public Bill(Customer customer) {
		orders = DAOFactory.getInstance().getBaseDAO().
				select(Order.class, "`CustomerID`=" + customer.getCustomerID());
	}
	
	public void pay() {
		for (Model order : orders) {
			DAOFactory.getInstance().getBaseDAO().delete(order);
		}
	}
	
	@Override
	public String toString() {
		StringBuilder bill = new StringBuilder();
		float sum = 0f;
		bill.append("********************\n");
		bill.append("      Paddy's\n");
		bill.append(" Self-Checkout pub\n");
		bill.append("  fiscal code: " + ((orders.size() == 0) ? 0 : ((Order)(orders.get(0))).getOrderID()) + "\n");
		bill.append("********************\n");
		for (Model m : orders) {
			Order order = (Order) m;
			Product product = (Product) DAOFactory.getInstance().getBaseDAO().
					select(Product.class, "`ProductID`=" + order.getProductID()).get(0);
			bill.append(product.getProductName() + "\n");
			String val = order.getQuantity() + " x " + product.getPrice();
			String price = new Float((order.getQuantity() * product.getPrice())).toString();
			sum += order.getQuantity() * product.getPrice();
			int spaces = 20 - val.length() - price.length();
			bill.append(val);
			for (int i = 0; i < spaces; ++i)
				bill.append(" ");
			bill.append(price + "\n");
		}
		bill.append("--------------------\n");
		String price = new Float(sum).toString();
		int spaces = 15 - price.length();
		bill.append("TOTAL");
		for (int i = 0; i < spaces; ++i)
			bill.append(" ");
		bill.append(price + "\n");
		bill.append("********************");
		return bill.toString();
	}
}
